<template>
  <el-dialog
    title="控制"
    v-model="state.show"
    width="550px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-form ref="formRef" label-width="60px">
      <el-form-item label="开关" prop="sw">
        <el-switch v-model="state.sw" :active-value = "1" :inactive-value = "0" @click="switchChange()" />
      </el-form-item>
      <el-form-item label="调光" prop="sl">
        <el-slider v-model="state.sl" :max="100" :min="0" @change="percentageChange()" />
      </el-form-item>
      <el-form-item label="定时" v-if="state.row.product.productKey == 'fHnYRFCEhDe5Z6he'"><!-- 4G灯控制电源(新创) -->
        <el-button type="primary" plain @click="handleSetting()">设置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 4G灯控制电源(新创)操作页面 -->
  <timingSetting ref="timingSettingRef" />
</template>
<script lang="ts" setup>
import { propertySet, getDevicesDetail } from '../api/devices.api'
import timingSetting from './timingSetting.vue'
// 引入公共方法获取设备属性
import { getDeviceProperties } from '@/utils/deviceUtils'

const state = reactive({
  show: false,
  row: {} as any,
  sw: 0,
  sl: 0,
  swName: '',
  slName: '',
  gwmac: '', // 微自然
})

// 定时
const timingSettingRef = ref()
const handleSetting = () => {
  timingSettingRef.value.openDialog(state.row)
}

const openDialog = (row: any) => {
  state.show = true
  state.row = row
  
  const { swName, slName, gwmac } = getDeviceProperties(row.product.productKey)
  state.swName = swName
  state.slName = slName
  // 单独处理微自然单灯控制器的 gwmac
  state.gwmac = row.product.productKey === 'hATm2Tswh3TDik8W' ? row.parentId : gwmac

  nextTick(async () => {
    // Object.assign(state.form, row)
    await Promise.all([sw_sl_property()])
  })
}

// 开关按钮
const switchChange = async () => {
  const args: Record<string, any> = {}
  args[state.swName] = state.sw
  if (state.gwmac) {
    args.gwmac = state.gwmac
  }
  propertySet({
    deviceId: state.row.deviceId,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '开关成功',
      })
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 调光按钮
const percentageChange = async () => {
  const args: Record<string, any> = {}
  args[state.slName] = state.sl
  if (state.gwmac) {
    args.gwmac = state.gwmac
  }
  propertySet({
    deviceId: state.row.deviceId,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '调光成功',
      })
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 开关属性数据
const sw_sl_property = () => {
  getDevicesDetail(state.row.deviceId)
  .then((res) => {
    state.sw = Number(res.data.property?.[state.swName]?.value) || 0
    state.sl = Number(res.data.property?.[state.slName]?.value) || 0
  })
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped>
.el-slider {
  padding: 10px 20px 10px 10px;
}
</style>